﻿using System;
using System.ComponentModel;
using System.Windows;
using Loki.Commands;
using Loki.UI.Wpf.Resources;

namespace Loki.UI.Wpf
{
    internal class WindowAdapter<TWindow, TViewModel> : ContentControlAdapter<TWindow, TViewModel>
        where TWindow : Window, IView<TViewModel>
        where TViewModel : class, IViewModel
    {
        public WindowAdapter(TWindow P_Window)
            : base(P_Window)
        {
            Control.Activated += ViewWindow_Activated;
            Control.Deactivated += ViewWindow_Deactivated;
            Control.Closing += ViewWindow_Closing;

            Control.DataContextChanged += ViewWindow_DataContextChanged;
        }

        private void ViewWindow_Closing(object P_Sender, CancelEventArgs e)
        {
            _IsClosing = true;
            if (ViewModel != null)
            {
                Log.InfoFormat("View {0} on {1} closing", Control.GetType(), ViewModel.GetType());
                ViewModel.Close.Execute(null);
            }
        }

        private void ViewWindow_DataContextChanged(object P_Sender, DependencyPropertyChangedEventArgs e)
        {
            if (ViewModel != null)
            {
                Commands.Handle(ViewModel.Close, ViewModel_CanClose, ViewModel_Close);
            }
        }

        protected virtual void ViewModel_CanClose(object P_Sender, CanExecuteCommandEventArgs e)
        {
            e.CanExecute = !_IsClosing;
        }

        private bool _IsClosing = false;

        protected virtual void ViewModel_Close(object P_Sender, CommandEventArgs e)
        {
            Log.InfoFormat("View {0} on {1} closing by VM", Control.GetType(), ViewModel.GetType());
            Control.Close();
        }

        private void ViewWindow_Deactivated(object sender, EventArgs e)
        {
            Log.DebugFormat(LogStrings.ControlAdapter_ViewDesactivated, Control.Title);
            ViewModel.Desactivate.Execute(null);
        }

        private void ViewWindow_Activated(object sender, EventArgs e)
        {
            Log.DebugFormat(LogStrings.ControlAdapter_ViewActivated, Control.Title);
            ViewModel.Activate.Execute(null);
        }
    }
}
